var editor, btn_danger_title, btn_danger_text, editor1;
var photo_num_type = 1, content_img = ".content-img-list_weitoutiao";
var imgFile = []; //文件流
var imgSrc = []; //图片路径
var imgName = []; //图片名字


$(function () {
    if (user_data == "") {
        alert("请先登录");
        window.location.href = "login.html?type_to=" + "publish";
        return
    }
    dirName = "ydupf/work";
    //设置页面的数据
    var userimg = getPicUrl(getAliossPath("user/" + user_data.id, user_data.headimg), 30, 0);
    $("#user_name").text(user_data.name)
    $(".img-circle").attr("src", userimg)


    var publish_type = $_GET["type"] ? $_GET["type"] : "wenzhang";
    switch (publish_type) {
        // case "xinwen":
        //     $(".publish_type").text("新闻");
        //     $(".publish_menu").append(
        //         '<div class="publish_menu_content" type="wenzhang">文章</div>' +
        //         '<div class="publish_menu_content" type="shipin">视频</div>' +
        //         '<div class="publish_menu_content" type="weitoutiao">微头条</div>'
        //     );
        //     $(".xinwen").show().siblings().hide();
        //     content_img=".content-img-list_xinwen";
        //     editor = "#editor_xinwen";
        //     break;
        case "wenzhang":
            $(".publish_type").text("文章");
            $(".publish_menu").append(
                '<div class="publish_menu_content" type="shipin">视频</div>' +
                '<div class="publish_menu_content" type="tuwen">图文</div>' +
                '<div class="publish_menu_content" type="weitoutiao">微头条</div>'
            );
            $(".wenzhang").show().siblings().hide();
            btn_danger_title = ".wenzhang_title";
            btn_danger_text = ".wenzhang_text";

            editor = "#editor_wenzhang";
            document.title = "发布文章";
            break;
        case "shipin":
            $(".publish_type").text("视频");
            $(".publish_menu").append(
                '<div class="publish_menu_content" type="wenzhang">文章</div>' +
                '<div class="publish_menu_content" type="tuwen">图文</div>' +
                '<div class="publish_menu_content" type="weitoutiao">微头条</div>'
            );
            $(".shipin").show().siblings().hide();
            btn_danger_title = ".shipin_title";
            btn_danger_text = ".shipin_text";
            document.title = "发布视频";
            break;
        case "tuwen":
            $(".publish_type").text("图文");
            $(".publish_menu").append(
                '<div class="publish_menu_content" type="wenzhang">文章</div>' +
                '<div class="publish_menu_content" type="shipin">视频</div>' +
                '<div class="publish_menu_content" type="weitoutiao">微头条</div>'
            );
            content_img = ".content-img-list_tuwen";
            photo_num_type = 9;
            btn_danger_title = ".tuwen_title";
            btn_danger_text = ".tuwen_text";
            uploadeid = "upload_ali_tuwen";
            $(".tuwen").show().siblings().hide();
            document.title = "发布图文";
            break;
        case "weitoutiao":
            $(".publish_type").text("微头条");
            $(".publish_menu").append(
                '<div class="publish_menu_content" type="wenzhang">文章</div>' +
                '<div class="publish_menu_content" type="shipin">视频</div>' +
                '<div class="publish_menu_content" type="tuwen">图文</div>'
            );
            $(".weitoutiao").show().siblings().hide();
            content_img = ".content-img-list_weitoutiao";
            photo_num_type = 9;
            editor = "#editor_weitoutiao";
            document.title = "发布微头条";
            uploadeid = "upload_ali_weitoutiao"
            break;
    }
    $(".publish_menu_content").on("click", function () {
        let menu_type = $(this).attr("type");
        window.location.href = "publish.html?type=" + menu_type;
    })
    $(".photo_num").on("click", function () {
        photo_num_type = $(this).attr("num_type");
        if (photo_num_type > $(".content-img-list").children("li").length) {
            $(".file").show();
        } else {
            $(".file").hide();
        }
    })
    $("#demo_shezhi").on("click", function () {
        let menu_type = $(this).attr("type");
        window.location.href = "create.html?type=" + menu_type;
    })


    $(".fanhui").hover(function () {
        $('.popover-toggle').popover('show')
    }, function () {
        $('.popover-toggle').popover('hide')
    })

    $(".fanhui").on("click", function () {
        window.location.href = "create.html?type=" + "zhuye";
    })


    // 用户显示设置
    $(".mengban2").click(function () {
        let type1 = $(".demo").is(":visible")
        let type2 = $(".publish_menu").is(":visible")
        if (type1) {
            $(".demo").hide();
            console.log(1)
        } else if (type2) {
            $(".publish_menu_but").find(".jiantou").removeClass("glyphicon-triangle-top");
            $(".publish_menu_but").find(".jiantou").addClass("glyphicon-triangle-bottom");
            $(".publish_menu").hide();
            console.log(2)
        }
        $(".mengban2").hide();
    })
    $(".yonghu,.demo").click(function () {
        $(".mengban2").show();
        $(".demo").css("left", $(".yonghu").offset().left);
        $(".demo").toggle();
    })

    $(".publish_menu_but").click(function () {
        $(".mengban2").show();
        $(this).find(".jiantou").removeClass("glyphicon-triangle-bottom");
        $(this).find(".jiantou").addClass("glyphicon-triangle-top");
        $(".publish_menu").css("left", $(".publish_menu_but").offset().left);
        $(".publish_menu").toggle();
    })


    //富文本编辑器
    if (editor) {
        const E = window.wangEditor
        editor1 = new E(editor)

        // editor1.config.uploadVideoServer = ""
        // editor1.config.uploadImgServer = "https://resource.beelink.com"
        editor1.config.uploadFileName = 'questionImg'
        editor1.config.uploadImgHeaders = {
            'authorities': authorities
        }


        editor1.config.uploadImgHooks = {
            customInsert: function (insertImgFn, result, editor) {
                insertImgFn(result.date[0]);
            }
        }
        editor1.config.height = 350
        editor1.create()


    }

    //如果有数据就填入
    var user_caogao = $.session.get("caogao") ? $.session.get("caogao") : null;
    if (user_caogao != null) {
        user_caogao = JSON.parse(user_caogao);
        $.session.remove("caogao");
        console.log(user_caogao)
        if (user_caogao.title){
            $(btn_danger_title).val(user_caogao.title);
        }
        if (user_caogao.introduce){
            $(btn_danger_text).val(user_caogao.introduce);
        }
        if (user_caogao.title){
            $(".article_title_wei").val(user_caogao.title);
        }
        if (user_caogao.content) {
            editor1.txt.html(user_caogao.content);
        }

    }


//保存草稿
    $("#btn-default").on("click", function () {
        var title, introduce, content, localStorage_num
        // window.localStorage.clear()
        if (window.localStorage.getItem("caogao")) {
            localStorage_num = JSON.parse(window.localStorage.getItem("caogao"));
        } else {
            localStorage_num = []
        }

        switch (publish_type) {
            case "wenzhang":
                title = $(btn_danger_title).val();
                introduce = $(btn_danger_text).val();
                content = editor1.txt.html()
                let data = {}
                data.type_type = "文章"
                data.title = title
                data.introduce = introduce
                data.content = content
                localStorage_num = JSON.stringify(localStorage_num.concat(data))
                window.localStorage.setItem("caogao", localStorage_num)

                window.location.href = "create.html"
                break
            case "shipin":
                title = $(btn_danger_title).val();
                introduce = $(btn_danger_text).val();
                let data2 = {};
                data2.type_type = "视频";
                data2.title = title;
                data2.introduce = introduce;
                data2.plic = "";

                localStorage_num = JSON.stringify(localStorage_num.concat(data2));
                window.localStorage.setItem("caogao", localStorage_num);
                // window.localStorage.clear();
                window.location.href = "create.html";
                break;
            case "tuwen":
                title = $(btn_danger_title).val();
                introduce = $(btn_danger_text).val();
                let data3 = {};
                data3.type_type = "图文";
                data3.title = title;
                data3.introduce = introduce;
                data3.plic = "";

                localStorage_num = JSON.stringify(localStorage_num.concat(data3));
                window.localStorage.setItem("caogao", localStorage_num);
                // // window.localStorage.clear();
                window.location.href = "create.html";
                break;
            case "weitoutiao":
                title = $(".article_title_wei").val();
                let data4 = {}
                data4.type_type = "微头条"
                data4.title = title;

                localStorage_num = JSON.stringify(localStorage_num.concat(data4))
                window.localStorage.setItem("caogao", localStorage_num)
                // window.localStorage.clear()
                window.location.href = "create.html"
                break
        }
    })

//发布
    $("#btn-danger").on("click", function () {
        var title = "", introduce = "", content = "", Tpics = "", tpic = "", tpicNumber = "";
        switch (publish_type) {
            case "wenzhang":
                title = $(btn_danger_title).val();
                introduce = $(btn_danger_text).val();
                content = editor1.txt.html()
                if (title == "") {
                    alert("请输入标题");
                    return;
                }
                if (introduce == "") {
                    alert("请输入摘要");
                    return;
                }
                if (content == "") {
                    alert("请输入正文");
                    return;
                }
                submit_wenzhang("article", title, introduce, 0, "", content, "", 0, 0);
                alert("发布成功");
                window.location.href = "create.html";
                break
            case "shipin":
                title = $(btn_danger_title).val();
                introduce = $(btn_danger_text).val();
                let video_tpic = Return_videotpic();
                content = video_tpic.video_name
                // tpic = "https://resource.beelink.com/ydupf/work/" + content + "?x-oss-process=video/snapshot,t_1,f_jpg,w_0,h_0,m_fast";
                tpic = video_tpic.img_name;
                let videoSize = video_tpic.size
                console.log(tpic)
                $("#output").attr("src", tpic);
                console.log(title, introduce, content, videoSize)
                submit_wenzhang("lvideo", title, introduce, 0, tpic, content, content, 0, videoSize);
                set_upload_param(uploader_video_img, '', false);
                set_upload_param(uploader_video, '', false);
                break
            case "tuwen":
                title = $(btn_danger_title).val();
                introduce = $(btn_danger_text).val();
                Tpics = ReturnTpic();
                tpic = Tpics.toString()
                tpicNumber = Tpics.length
                for (let i = 0; i < Tpics.length; i++) {
                    let data = Tpics[i]
                    if (content == "") {
                        content = data + "|ymkjtext|";
                    } else {
                        content += "|ymkjimg|" + data + "|ymkjtext|";
                    }
                }
                submit_wenzhang("imgtext", title, introduce, tpicNumber, tpic, content, "", 0, 0);
                set_upload_param(uploader, '', false);
                break
            case "weitoutiao":
                content = $(".article_title_wei").val();
                Tpics = ReturnTpic();
                tpic = Tpics.toString()
                tpicNumber = Tpics.length
                submit_wenzhang("headlines", content, "", tpicNumber, tpic, content, "", 0, 0);
                set_upload_param(uploader, '', false);
                break
        }

    })

})


//上传到后台
function submit_wenzhang(type, title, introduce, tpicNumber, tpic, content, videoPath, videoLength, videoSize) {
    /// type 类别,新闻:news,微头条;headlines,文章:article,图文:imgtext,长视频:lvideo,短视频:svideo
    /// title 新闻,文章,短视频,长视频的标题
    /// introduce 视频的简介
    /// tpicNumber 新闻或者文章封面图展示数量,图文中图的数量
    /// tpic 新闻,文章,图文,短视频和长视频的封面地址,每个地址使用逗号分隔;微头条中的图片
    /// content 内容:新闻,微头条,文章的内容;长视频和短视频的链接;图文中每个图片开始和结束用\"|ymkjimg|\"进行分隔,图文中每个图片对应的介绍开始和结束使用\"|ymkjtext|\"进行分隔,
    /// videoLength 视频的时长(分钟)
    /// videoSize 视频的大小(M)]
    /// onSendProgress 上传进度回调，用来指示传输进度，形式为onSendProgress(received, total)
    $.ajax({
        url: baseURL + '/webapi/works/addWorks',
        type: 'post',
        dataType: 'json',
        async: false,//同步
        headers: {'authorities': authorities},
        data: {
            "type": type,
            "title": title,
            "introduce": introduce,
            "tpicNumber": tpicNumber,
            "tpic": tpic,
            "content": content,
            "videoPath": videoPath,
            "videoLength": videoLength,
            "videoSize": videoSize,
        },
        success: function (data) {
            console.log(data)
            if (data.code == 1) {
                console.log("发布成功")
                dirName = dirName + "/" + data.data
            } else if (data.code == "401") {
                alert("账号在别处登录，请重新登录")
                window.location.href = "login.html"
            } else {
                alert(data.msg)
            }
        }
    })
}


// //上传视频
// var $file = $("#selectfile");
// $file.bind("change", function () {
//     GetFile($file.get(0).files);
// });
// //声明一个formdata 用来上传
// var UForm = new FormData();
// $("#Up").on("click", function () {
//     DoUp();
// });
// var $drop = $("#drop");
// with ($drop) {
//     on("dragenter", function () {
//         $drop.addClass("drag_hover");
//     });
//     on("dragleave", function () {
//         $drop.removeClass("drag_hover");
//     });
//     on("dragover", function (e) {
//         e.originalEvent.dataTransfer.dragEffect = 'copy';
//         e.preventDefault();
//     });
//     on("drop", function (e) {
//         e.preventDefault();
//         var files = e.originalEvent.dataTransfer.files;
//         $drop.removeClass("drag_hover");
//         if (files.length !== 0) {
//             GetFile(files);
//         }
//         ;
//     });
// }
//
// function GetFile(files) {
//     var file = files ? files[0] : false;
//     if (!file) {
//         return false;
//     };
//     UForm.append("file", file);//把要上传的视频放到UFom里
//     UForm.append("path", "ydupf/work/");//把要上传的视频放到UFom里
//     var reader = new FileReader();
//     reader.onload = function () {
//         $drop.html("<div class='row'><div id='video' class=''></div><div id='img' class=''></div></div>");
//         var html = "<video src='" + URL.createObjectURL(file) + "' controls />";
//         var $video = $(html).appendTo($drop.find("#video"));
//         with ($video) {
//             on("error", function () {
//                 alert("加载视频失败!请上传正确的视频！");
//                 return false;
//             });
//             on("loadeddata", function () {
//                 // MakePoster($video[0]);
//             });
//         }
//         ;
//     };
//     reader.readAsDataURL(file);
// };
//
// function MakePoster(video) {
//     // //canvas转Blob
//     // var dataURLtoBlob = function (dataurl) {
//     //     var arr = dataurl.split(','),
//     //         mime = arr[0].match(/:(.*?);/)[1],
//     //         bstr = atob(arr[1]),
//     //         n = bstr.length,
//     //         u8arr = new Uint8Array(n);
//     //     while (n--) {
//     //         u8arr[n] = bstr.charCodeAt(n);
//     //     }
//     //     return new Blob([u8arr], {type: mime});
//     // };
//     // var scale = 0.7;//截图绽放比例
//     // var canvas = document.createElement("canvas");
//     // canvas.width = video.videoWidth * scale;
//     // canvas.height = video.videoHeight * scale;
//     // canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
//     // var imgsrc = canvas.toDataURL('image/jpeg');//第二个参数指图片质量
//     // var poster = dataURLtoBlob(imgsrc);
//     // UForm.append("fengmian", poster);//把要上传的封面图片放到UFom里
//     // $drop.find("#img").append('<img src="' + imgsrc + '">');
// }
//
// function DoUp() {
//     $.ajax({
//         url: "https://trial.beelink.com:10021/admin/api/uploadFile",
//         type: "POST",
//         data: UForm,
//         async: false,
//         headers: {'authorities': "f7399e1b-56ba-4818-b13d-fd1627f79c66"},
//         processData: false,
//         contentType: false,
//         success: function (data) {
//             return data.msg;
//         },
//         error: function (e) {
//             console.log(e);
//         },
//     });
// }